﻿using Dapper;
using PersonalWebsite.Core.CQRS;
using PersonalWebsite.Core.Result;
using System.Diagnostics.CodeAnalysis;

namespace PersonalWebsite.Application.Queries.Post;

public class GetPostCategoryVO
{
    public int Id { get; init; }
    public string Name { get; init; }
}

public record GetPostCategoryQuery : IQuery<ApiResult<List<GetPostCategoryVO>>, List<GetPostCategoryVO>>
{
}

public class GetPostCategoryQueryHandler : QueryHandler<GetPostCategoryQuery, ApiResult<List<GetPostCategoryVO>>, List<GetPostCategoryVO>>
{
    private readonly IDBConnectionFactory dBConnectionFactory;

    public GetPostCategoryQueryHandler(IDBConnectionFactory dBConnectionFactory) : base(dBConnectionFactory)
    {
        this.dBConnectionFactory = dBConnectionFactory;
    }

    public override async Task<ApiResult<List<GetPostCategoryVO>>> Handle(GetPostCategoryQuery request, CancellationToken cancellationToken)
    {


        using var dbConnection = dBConnectionFactory.GetDbConnection();

        string sql = @$"SELECT  Id,  Category AS `Name` FROM WP_Post
                        GROUP BY Category ORDER BY Id";

        var result = await dbConnection.QueryAsync<GetPostCategoryVO>(sql);

        return await Task.FromResult(ApiResult<List<GetPostCategoryVO>>.Success(result?.ToList()));
    }
}

